import router from "@/router";
import { login, logout } from "@/utils/api/login";
import { getToken, removeToken, setToken } from "@/utils/auth";
import { ElMessage } from "element-plus";
import { defineStore } from "pinia";

const useUserStore = defineStore("user", {
  state: () => ({
    token: getToken(),
    name: "",
    // 头像url
    avatar: ""
  }),
  actions: {
    // 登录
    login(userInfo: any) {
      const mobile = userInfo.mobile.trim();
      const password = userInfo.password;
      return new Promise((resolve, reject) => {
        login(mobile, password)
          .then((res: any) => {
            console.log(res.data);
            this.token = res.data.token;
            setToken(res.data.token);
            this.avatar = res.data.avatar.file_path ? "http://localhost:7345/upload/" + res.data.avatar.file_path : "";
            router.push("/home");
            resolve("ok");
          })
          .catch((error: any) => {
            reject(error);
          });
      });
    },
    // 退出系统
    logout() {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          ElMessage({
            message: "记得常回家看看",
            type: "success"
          });
          this.token = "";
          router.push("/login");
          removeToken();
          resolve("ok");
        }).catch((error: any) => {
          reject(error);
        });
      });
    }
  }
});

export default useUserStore;
